#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_pwm.h"

#define PWM_GPIO       2
#define PWM_GPIO_CH    2
static volatile int g_buttonPressed = 0;
static const uint16_t g_tuneFreqs[] = {
   0, // 160M Hz 对应的分频系数：
   4186,// 1046.5
   4700, // 1174.7
   5276, // 1318.5
   5588,// 1396.9
   6272,// 1568
   7040,// 1760
   7902,// 1975.5
   3136// 5_ 783.99 // 第一个八度的 5
};
// 曲谱音符
static const uint8_t g_scoreNotes[] = {
   // 《两只老虎》简谱
   1, 2, 3, 1,        1, 2, 3, 1,        3, 4, 5,  3, 4, 5,
   5, 6, 5, 4, 3, 1,  5, 6, 5, 4, 3, 1,  1, 8, 1,  1, 8, 1, 
};
// 曲谱时值
static const uint8_t g_scoreDurations[] = {
   4, 4, 4, 4,        4, 4, 4, 4,        4, 4, 8,  4, 4, 8,
   3, 1, 3, 1, 4, 4,  3, 1, 3, 1, 4, 4,  4, 4, 8,  4, 4, 8,
};
//蜂鸣器播放任务
void *buzzerMusicTask(const char *arg)
{
   printf("buzzerMusicTask start!\r\n");
   for (size_t i = 0; i < sizeof(g_scoreNotes)/sizeof(g_scoreNotes[0]); i++) {
      uint32_t tune = g_scoreNotes[i]; // 音符
      uint16_t freqDivisor = g_tuneFreqs[tune];
      uint32_t tuneInterval = g_scoreDurations[i] * (125*1000); // 音符时间
      printf("%d %d %d %d\r\n", tune, (160*1000*1000) / freqDivisor, freqDivisor, tuneInterval);
      IoTPwmStart(PWM_GPIO_CH, 50, freqDivisor);
      usleep(tuneInterval);
      IoTPwmStop(PWM_GPIO_CH);
      usleep(100000);
   }
   return NULL;
}
//创建蜂鸣器播放任务
static void StartBeepMusicTask(void)
{
   osThreadAttr_t attr;
   // init gpio of beer
   IoTGpioInit(PWM_GPIO);
   // set the GPIO_2 multiplexing function to PWM
   IoTGpioSetFunc(PWM_GPIO, IOT_GPIO_FUNC_GPIO_2_PWM2_OUT);
   // set GPIO_2 is output mode
   IoTGpioSetDir(PWM_GPIO, IOT_GPIO_DIR_OUT);
   // init PWM2
   IoTPwmInit(PWM_GPIO_CH);
   attr.name = "buzzerMusicTask";
   attr.attr_bits = 0U;
   attr.cb_mem = NULL;
   attr.cb_size = 0U;
   attr.stack_mem = NULL;
   attr.stack_size = 1024;
   attr.priority = osPriorityNormal;
   if (osThreadNew((osThreadFunc_t)buzzerMusicTask, NULL, &attr) == NULL) {
      printf("[LedExample] Falied to create buzzerMusicTask!\n");
   }
}
//加入到系统运行
SYS_RUN(StartBeepMusicTask);